$(function () {
	/******************************************初始化部分******************************************/
	const table = layui.table;
	const element = layui.element;
	// 当前的tabindex值
	let tabIndex = 0;
	let tabToType = [1, 4, 2]
	// 数据产品请求参数
	let dataProductParams = {
		sourceType: 1,//产品类型 1-在线产品 2-套餐产品 4-离线产品
		ownUserId: sessionStorage.getItem('UserId'),
		currPage: 0,
		pageSize: 10
	}
	// 选中的数据产品的id list
	let productIdList = []
	// 产品表格实例
	const dataProductTable = table.render({
		elem: '#dataProductTable'
		, height: '.layui-tab-item'
		, cols: [[ //表头
			{ type: 'checkbox', width: 60 },
			{ type: 'numbers', title: '序号', width: 60 }
			, { field: 'productName', title: '产品名称' }
			, {
				field: 'status', title: '状态', sort: true, templet: function (d) {
					switch (d.status) {
						case -2:
							return `<span>审核失败</span>`
						case -1:
							return `<span>保存</span>`
						case 0:
							return `<span>正常（上架）</span>`
						case 1:
							return `<span>故障（下架）</span>`
						case 2:
							return `<span>未审核</span>`
						case 3:
							return `<span>未测试</span>`

					}
				}
			}
			, { field: 'brief', title: '简介', }
			, { field: 'buyCount', title: '申购次数' }
			, {
				title: '操作', width: 300, templet: function (d) {
					switch (d.status) {
						case 0:
							return `
						<a class="layui-btn layui-btn-danger layui-btn-xs text-white" lay-event="delete">删除</a>
						<a class="layui-btn  layui-btn-xs text-white" lay-event="edit">修改</a>
						<a class="layui-btn  layui-btn-xs text-white" lay-event="detail">详情</a>
						<a class="layui-btn  layui-btn-xs text-white" lay-event="takedown">下架</a>
						<a class="layui-btn  layui-btn-xs text-white" lay-event="test">测试</a>
                `
						case 1:
							return `
						<a class="layui-btn layui-btn-danger layui-btn-xs text-white" lay-event="delete">删除</a>
						<a class="layui-btn  layui-btn-xs text-white" lay-event="edit">修改</a>
						<a class="layui-btn  layui-btn-xs text-white" lay-event="shelves">上架</a>
						<a class="layui-btn  layui-btn-xs text-white" lay-event="test">测试</a>
                `
						default:
							return `
						<a class="layui-btn layui-btn-danger layui-btn-xs text-white" lay-event="delete">删除</a>
						<a class="layui-btn  layui-btn-xs text-white" lay-event="edit">修改</a>
						<a class="layui-btn  layui-btn-xs text-white" lay-event="test">测试</a>
                `
					}

				}
			},
		]]
	})
	/******************************************事件处理部分******************************************/
	// 表格操作 修改和删除
	table.on('tool(productTable)', function (obj) {
		const data = obj.data;
		if (obj.event === 'edit') {
			console.log('edit按钮')
			window.dataProductId = data.id;
			// window.location.href = `./popupPage/productRegistryPop.html?id=${data.id}`;
			layer.open({
				type: 2,
				title: "产品修改",
				area: ['1000px', '600px'],
				content: `./popupPage/productRegistryPop.html?id=${data.id}`,
				success: function () {
					console.log('打开弹窗 里面')
				},
				end: function () {
					productTableRender(data.sourceType)
				}
			});
		}
		else if (obj.event === 'delete') {
			$.ajax({
				timeout: 30000,
				url: window.Http + `/dataProduct/${data.id}`,
				type: 'DELETE',
				headers: {
					'Authorization': "Bearer " + sessionStorage.getItem('Token')
				},
				success: function (res) {
					if (res.code === 200) {
						layer.msg('删除成功')
						productTableRender(tabToType[tabIndex])
					} else {
						layer.msg(res.msg)
						productTableRender(tabToType[tabIndex])
					}
				}
			})
		} else if (obj.event === 'shelves') {//上架
			$.ajax({
				timeout: 30000,
				url: window.Http + "/dataProduct/operate",
				type: 'POST',
				headers: {
					'Authorization': "Bearer " + sessionStorage.getItem('Token')
				},
				data: JSON.stringify({
					status: 1,
					id: data.id
				}),
				contentType: 'application/json;charset=utf-8',
				success: function (res) {
					if (res.code === 200) {
						layer.msg('上架成功')
						productTableRender(tabToType[tabIndex])
					} else {
						layer.msg(res.msg)
					}
				}
			})
		} else if (obj.event === 'takedown') {//下架
			$.ajax({
				timeout: 30000,
				url: window.Http + "/dataProduct/operate",
				type: 'POST',
				headers: {
					'Authorization': "Bearer " + sessionStorage.getItem('Token')
				},
				data: JSON.stringify({
					status: -1,
					id: data.id
				}),
				contentType: 'application/json;charset=utf-8',
				success: function (res) {
					if (res.code === 200) {
						layer.msg('下架成功')
						productTableRender(tabToType[tabIndex])
					} else {
						layer.msg(res.msg)
					}
				}
			})
		} else if (obj.event === 'detail') {//详情 只有上架之后才有详情
			window.location.href = './productDetail.html?productId=' + data.id;
		} else if (obj.event === 'test') {//测试
			let testLoad = layer.load(1);
			$.ajax({
				timeout: 30000,
				url: window.Http + '/dataProduct/execute',
				type: 'POST',
				headers: {
					'Authorization': "Bearer " + sessionStorage.getItem('Token')
				},
				contentType: 'application/json',
				data: JSON.stringify({
					type: 1,
					productId: data.id
				}),
				success: function (res) {
					if (res.code === 200 && res.data.RetCode === 0) {
						console.log('测试', res)
						layer.msg('测试通过')
						layer.close(testLoad);
					} else {
						layer.msg(res.data?.ErrorMsg || res.msg || '测试失败')
						layer.close(testLoad);
					}
				},
				error:function () {
					layer.close(testLoad);
					layer.msg('测试请求失败')
				}
			})
		}
	})
	// 表格复选框选中事件
	table.on('checkbox(productTable)', function (obj) {
		if (obj.type === 'all' && obj.checked) {
			productIdList = table.cache['dataProductTable'].map(item => item.id);
			// console.log('ids', ids)
		} else if (obj.type === 'one' && obj.checked) {//选中
			productIdList.push(obj.data.id)
			console.log('sourceIdList', productIdList)
		} else if (obj.type === 'all' && !obj.checked) {//取消选中
			productIdList = []
		} else if (obj.type === 'one' && !obj.checked) {//取消选中
			// 查找值的索引
			const index = productIdList.indexOf(obj.data.id);
			if (index !== -1) {
				productIdList.splice(index, 1);
			}
		}
	});
	// 批量提交审核数据产品按钮
	$("#submitDataProductAll").on('click', function () {
		console.log('点击审核数据产品注册')
		if (productIdList.length > 0) {
			$.ajax({
				timeout: 30000,
				url: window.Http + '/dataProduct/commit/' + productIdList.join(','),
				type: 'PUT',
				headers: {
					'Authorization': "Bearer " + sessionStorage.getItem('Token')
				},
				data: {
					ids: productIdList.join(','),
					type: 1//1数据产品
				},
				success: function (res) {
					if (res.code === 200) {
						layer.msg('提交成功')
						productIdList = []
					} else {
						layer.msg(res.msg)
					}
				}
			})
		} else {
			layer.msg('当前未选中数据')
		}
	})
	// 批量删除数据产品按钮
	$('#deleteDataProductAll').on('click', function () {
		console.log("触发了")
		if (productIdList.length > 0) {
			$.ajax({
				timeout: 30000,
				url: window.Http + '/dataProduct/' + productIdList.join(','),
				type: 'DELETE',
				headers: {
					'Authorization': "Bearer " + sessionStorage.getItem('Token')
				},
				success: function (res) {
					if (res.code === 200) {
						layer.msg('删除成功')
						productIdList = []
						productTableRender(tabToType[tabIndex])
					} else {
						layer.msg(res.msg)
					}
				}
			})
		} else {
			layer.msg('当前未选中数据')
		}
	})
	// 选项卡切换 0-在线数据产品，1-离线数据产品 2-套餐数据产品
	element.on('tab(productTab)', function (data) {
		console.log(data.index, typeof data.index); //得到当前Tab的所在下标
		tabIndex = data.index
		if (data.index === 0) {
			productTableRender(1)
			productIdList = []
		} else if (data.index === 1) {
			productTableRender(4)
			productIdList = []
		} else if (data.index === 2) {
			productTableRender(2)
			productIdList = []
		}
	});
	// 注册部分
	// 数据产品注册
	$("#productRegistration").click(function () {
		console.log('点击数据产品注册')
		window.dataProductId = null;
		layer.open({
			type: 2,
			title: "数据产品注册",
			area: ['1000px', '600px'],
			content: './popupPage/productRegistryPop.html',
			success: function () {
				console.log('打开弹窗 外面')
			},
			end: function () {
				// productListReq(data.sourceType)
				// 把tab设为第一个在线产品
				element.tabChange('productTab','online')
				console.log('tabIndex', tabIndex)
				productTableRender(1)
			}
		});
		// window.location.href = `./popupPage/productRegistryPop.html`;
	})
	/******************************************功能函数部分******************************************/
	/**
	 * @Date：2023-09-23, 周六, 15:53
	 * @description: 请求产品列表 并渲染表格
	 * @param   {Object} params 请求参数 产品类型 1-在线产品 2-套餐产品 4-离线产品
	 * @return {Promise} 请求的结果
	 */
	function productListReq(params) {
		return new Promise((function (resolve, reject) {
			$.ajax({
				timeout: 30000,
				url: window.Http + "/dataProduct/list",
				type: 'GET',
				headers: {
					'Authorization': "Bearer " + sessionStorage.getItem('Token')
				},
				data: params,
				success: function (res) {
					if (res.code === 200) {
						resolve(res)
					} else {
						layer.msg(res.msg)
						reject(new Error("请求失败")); // 失败时将错误传递给调用者
					}
				}
			})
		}))
	}
	/**
	 * @description:函数描述 渲染表格和分页
	 * @return 返回值 无
	 * @param type {Number} 产品类型 1-在线产品 2-套餐产品 4-离线产品
	 */
	function productTableRender(type) {
		dataProductParams.sourceType = type
		productListReq(dataProductParams).then(res => {
			dataProductTable.reload({ data: res.rows })
			layui.laypage.render({
				elem: 'dataProductTablePage', //注意，这里的 test1 是 ID，不用加 # 号
				count: res.total, //数据总数，从服务端得到
				limit: 10,
				groups: 5,
				jump: function (obj, first) {
					if (!first) {
						console.log('obj.curr', obj.curr)
						dataProductParams.currPage = obj.curr
						productListReq(dataProductParams).then(res => {
							productListReq.reload({ data: res.rows })
						});
					}
				}
			});
		})
	}
	productTableRender(1)
	// 统计条数
	function requestStatistic(Type) {
		$.ajax({
			timeout: 30000,
			url: window.Http + "/count/personal/data/table",
			type: 'GET',
			headers: {
				'Authorization': "Bearer " + sessionStorage.getItem('Token')
			},
			data: { type: Type, ownUserId: sessionStorage.getItem('UserId') },
			success: function (res) {
				if (res.code === 200) {
					if (Type === 1) {
						$('.dataProductTotal').html(res.data.total || 0);
						$('.dataProductStatus').html(res.data.normal || 0);
						$('.buyCount').html(res.data.buyNum || 0);
					} else {
						$('.datasourceTotal').html(res.data.total || 0);
						$('.datasourceStatus').html(res.data.normal || 0);
					}
				}
			}
		})
	}
	requestStatistic(1)
	requestStatistic(0)
})
